package com.qf.j2112.aspect;

import com.qf.j2112.anno.JWTAnno;
import com.qf.j2112.po.SysLog;
import com.qf.j2112.service.SysLogService;
import com.qf.j2112.utils.IpUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Date;

@Component
@Aspect
public class LogAspect {

    @Resource
    SysLogService sysLogService;

    //定义切点
    @Pointcut("@annotation(com.qf.j2112.anno.JWTAnno)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        String name = joinPoint.getSignature().getName();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        //获取代理的方法对象
        Method method = methodSignature.getMethod();
        //获取代理前的方法前的注解
        JWTAnno anno = method.getAnnotation(JWTAnno.class);
        SysLog log = new SysLog();
        String ip = IpUtil.getRemoteIp();

        String userAction = null;

        if (anno != null) {
            userAction = anno.name();
            log.setAction(userAction);
            log.setCreateTime(new Date());
            log.setIp(ip);

            //???如何获得用户id和用户姓名
            log.setUid(0);
            log.setUname("test");
            //????

            //向数据库添加日志
            sysLogService.addSysLog(log);
        }
        //前置
        System.out.println("动作为:  " + name+" 。ip ："+IpUtil.getRemoteIp());
        Object proceed = joinPoint.proceed(); //方法本身执行逻辑
        //后置位置
        return proceed;
    }


}


